<template>
  <div class="awards-manager">
    <!-- 获奖情况列表 -->
    <div class="awards-list">
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-else-if="awards.length === 0" class="empty-text">暂无获奖情况</div>
      <ul v-else class="experience-list">
        <li v-for="award in awards" :key="award.id" class="award-item">

          <!-- 获奖信息 -->
          <div class="award-content">
            <span class="award-name">{{ award.awardName }}</span>
            <span v-if="award.awardLevel || award.awardingOrganization || award.awardTime" class="award-extra">
              （{{ [award.awardLevel, award.awardingOrganization, formatDate(award.awardTime)].filter(Boolean).join('，') }}）
            </span>
          </div>
          <!-- 操作按钮 -->
          <div class="award-actions">
            <button @click="editAward(award)" class="action-btn edit-btn" title="编辑">✏️</button>
            <button @click="confirmDeleteAward(award)" class="action-btn delete-btn" title="删除">🗑️</button>
          </div>


        </li>
      </ul>
    </div>

    <!-- 添加按钮 -->
    <div class="add-button-container">
      <button @click="addAward" class="add-btn">
        <span class="add-icon">+</span>
        添加获奖情况
      </button>
    </div>

    <!-- 添加/编辑获奖情况弹窗 -->
    <div v-if="showAwardModal" class="modal-overlay" @click="closeAwardModal">
      <div class="modal-content award-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑获奖情况' : '添加获奖情况' }}</h3>
          <button class="close-btn" @click="closeAwardModal">×</button>
        </div>
        <div class="modal-body">
          <form class="award-form">
            <div class="form-group">
              <label>奖项名称 <span class="required">*</span></label>
              <input 
                v-model="awardForm.awardName" 
                type="text" 
                class="form-input"
                placeholder="请输入奖项名称"
                maxlength="200"
              />
            </div>
            
            <div class="form-group">
              <label>奖项级别</label>
              <input 
                v-model="awardForm.awardLevel" 
                type="text" 
                class="form-input"
                placeholder="如：国家级、省级、市级等"
                maxlength="100"
              />
            </div>
            
            <div class="form-group">
              <label>颁奖机构</label>
              <input 
                v-model="awardForm.awardingOrganization" 
                type="text" 
                class="form-input"
                placeholder="请输入颁奖机构名称"
                maxlength="200"
              />
            </div>
            
            <div class="form-group">
              <label>获奖时间</label>
              <input 
                v-model="awardForm.awardTime" 
                type="date" 
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label>获奖描述</label>
              <textarea 
                v-model="awardForm.awardDescription" 
                class="form-textarea"
                placeholder="请描述获奖的相关情况（可选）"
                maxlength="500"
              ></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAwardModal" :disabled="saving">取消</button>
          <button class="confirm-btn" @click="saveAward" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="warning-icon">⚠️</div>
          </div>
          <p class="modal-text">确定要删除这个获奖情况吗？</p>
          <p class="modal-subtitle">「{{ deleteTarget?.awardName }}」</p>
          <p class="modal-hint">删除后无法恢复</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDeleteModal" :disabled="deleting">取消</button>
          <button class="confirm-btn delete-confirm" @click="deleteAward" :disabled="deleting">
            {{ deleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示弹窗 -->
    <div v-if="showMessageModal" class="modal-overlay" @click="closeMessageModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header" :class="messageType === 'success' ? 'success-header' : 'error-header'">
          <h3>{{ messageTitle }}</h3>
          <button class="close-btn" @click="closeMessageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="message-icon" :class="messageType === 'success' ? 'success-icon' : 'error-icon'">
              {{ messageType === 'success' ? '✓' : '✗' }}
            </div>
          </div>
          <p class="modal-text">{{ messageText }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeMessageModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { 
  getStudentAwardsService, 
  addStudentAwardService, 
  updateStudentAwardService, 
  deleteStudentAwardService 
} from '@/api/student.js'

// 数据状态
const awards = ref([])
const loading = ref(false)

// 添加/编辑弹窗状态
const showAwardModal = ref(false)
const isEditing = ref(false)
const currentAwardId = ref(null)
const saving = ref(false)
const awardForm = ref({
  awardName: '',
  awardLevel: '',
  awardingOrganization: '',
  awardTime: '',
  awardDescription: ''
})

// 删除弹窗状态
const showDeleteModal = ref(false)
const deleteTarget = ref(null)
const deleting = ref(false)

// 消息提示弹窗状态
const showMessageModal = ref(false)
const messageTitle = ref('')
const messageText = ref('')
const messageType = ref('success')

// 组件挂载时加载数据
onMounted(() => {
  fetchAwards()
})

// 获取获奖情况列表
const fetchAwards = async () => {
  loading.value = true
  try {
    const result = await getStudentAwardsService()
    if (result.code === 200) {
      awards.value = result.data || []
    } else {
      console.error('获取获奖情况失败:', result.msg)
      awards.value = []
    }
  } catch (error) {
    console.error('获取获奖情况异常:', error)
    awards.value = []
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 添加获奖情况
const addAward = () => {
  isEditing.value = false
  currentAwardId.value = null
  awardForm.value = {
    awardName: '',
    awardLevel: '',
    awardingOrganization: '',
    awardTime: '',
    awardDescription: ''
  }
  showAwardModal.value = true
}

// 编辑获奖情况
const editAward = (award) => {
  isEditing.value = true
  currentAwardId.value = award.id
  awardForm.value = {
    awardName: award.awardName || '',
    awardLevel: award.awardLevel || '',
    awardingOrganization: award.awardingOrganization || '',
    awardTime: award.awardTime || '',
    awardDescription: award.awardDescription || ''
  }
  showAwardModal.value = true
}

// 关闭添加/编辑弹窗
const closeAwardModal = () => {
  showAwardModal.value = false
  awardForm.value = {
    awardName: '',
    awardLevel: '',
    awardingOrganization: '',
    awardTime: '',
    awardDescription: ''
  }
}

// 保存获奖情况
const saveAward = async () => {
  if (!awardForm.value.awardName.trim()) {
    showErrorMessage('请输入奖项名称')
    return
  }

  saving.value = true
  try {
    let result
    if (isEditing.value) {
      // 编辑模式
      result = await updateStudentAwardService(currentAwardId.value, {
        id: currentAwardId.value,
        ...awardForm.value
      })
    } else {
      // 添加模式
      result = await addStudentAwardService(awardForm.value)
    }

    if (result.code === 200) {
      closeAwardModal()
      await fetchAwards() // 重新加载数据
      showSuccessMessage(isEditing.value ? '获奖情况更新成功' : '获奖情况添加成功')
    } else {
      showErrorMessage(result.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存获奖情况异常:', error)
    let errorMessage = '保存获奖情况时发生错误，请稍后重试'
    
    if (error && error.code && error.msg) {
      errorMessage = error.msg
    } else if (error && error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg
    }
    
    showErrorMessage(errorMessage)
  } finally {
    saving.value = false
  }
}

// 确认删除获奖情况
const confirmDeleteAward = (award) => {
  deleteTarget.value = award
  showDeleteModal.value = true
}

// 关闭删除确认弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteTarget.value = null
}

// 删除获奖情况
const deleteAward = async () => {
  if (!deleteTarget.value) return
  
  deleting.value = true
  try {
    const result = await deleteStudentAwardService(deleteTarget.value.id)
    if (result.code === 200) {
      closeDeleteModal()
      await fetchAwards() // 重新加载数据
      showSuccessMessage('获奖情况删除成功')
    } else {
      showErrorMessage(result.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除获奖情况异常:', error)
    showErrorMessage('删除获奖情况时发生错误，请稍后重试')
  } finally {
    deleting.value = false
  }
}

// 显示成功消息
const showSuccessMessage = (text) => {
  messageType.value = 'success'
  messageTitle.value = '操作成功'
  messageText.value = text
  showMessageModal.value = true
}

// 显示错误消息
const showErrorMessage = (text) => {
  messageType.value = 'error'
  messageTitle.value = '操作失败'
  messageText.value = text
  showMessageModal.value = true
}

// 关闭消息弹窗
const closeMessageModal = () => {
  showMessageModal.value = false
}
</script>

<style scoped>
/* 主容器 */
.awards-manager {
  max-width: 800px;
  margin: 0 auto;
}

/* 获奖情况列表 */
.awards-list {
  margin-bottom: 30px;
}

.loading-text, .empty-text {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 16px;
}

.experience-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.award-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.award-item:last-child {
  border-bottom: none;
}

.award-content {
  flex: 1;
  margin-right: 15px;
}

.award-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 5px;
}

.award-extra {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.award-actions {
  display: flex;
  gap: 5px;
  flex-shrink: 0;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s ease;
}

.edit-btn {
  background: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background: #bbdefb;
}

.delete-btn {
  background: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background: #ffcdd2;
}

/* 添加按钮 */
.add-button-container {
  text-align: center;
}

.add-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.add-icon {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 15px;
  max-width: 500px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
  padding: 20px 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.success-header h3 {
  color: #4caf50;
}

.error-header h3 {
  color: #f44336;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 0 20px 20px;
}

.award-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #f44336;
}

.form-input, .form-textarea {
  padding: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s ease;
  font-family: inherit;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-footer {
  padding: 0 20px 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover:not(:disabled) {
  background: #e0e0e0;
}

.confirm-btn {
  background: #667eea;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background: #5a67d8;
}

.confirm-btn:disabled, .cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.delete-confirm {
  background: #f44336;
}

.delete-confirm:hover:not(:disabled) {
  background: #d32f2f;
}

/* 消息弹窗特殊样式 */
.icon-wrapper {
  text-align: center;
  margin-bottom: 15px;
}

.warning-icon, .message-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.success-icon {
  color: #4caf50;
}

.error-icon {
  color: #f44336;
}

.modal-text {
  text-align: center;
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
}

.modal-subtitle {
  text-align: center;
  font-size: 14px;
  color: #667eea;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.modal-hint {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .modal-overlay {
    padding: 10px;
  }
  
  .award-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .award-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .modal-content {
    max-height: 95vh;
  }
}
</style>
